package keter.ssh;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.util.concurrent.ListenableFuture;

import keter.framework.AbstractBaseSSHConfig;
import keter.ssh.cli.Parser;
import keter.ssh.core.SshUtil;
import keter.ssh.exec.CmdExecutor;
import keter.ssh.exec.HostsExecutor;
import keter.ssh.hosts.Assembler;
import keter.ssh.hosts.Fetcher;
import keter.ssh.hosts.SimpleFetcher;

public class SshBatchMain extends AbstractBaseSSHConfig{

	/**
	 * Logger for this class
	 */
	private static final Logger logger = LoggerFactory.getLogger(SshBatchMain.class);
	
	private static boolean hostsReady;
	
	public static boolean isHostsReady() {
		return hostsReady;
	}

	public static void setHostsReady(boolean hostsReady) {
		SshBatchMain.hostsReady = hostsReady;
	}

	public static Fetcher getFetcher(){
		return new SimpleFetcher();
	}
	
	/**
	 * 功能描述
	 * @param configUrl
	 * @param args
	 * @throws Exception 
	 * @author gulixing@msn.com
	 * @date   2016年7月27日
	 */
	public static void init(String configUri) throws Exception{
		useConfig(configUri);
		//初始化执行机
		CmdExecutor.init(
			prop.getInt("thread")		
		);
	}
	
	public static void fire(String[] args) throws Exception{
		if(args!=null && args.length>0){
			//卍解！！
			Parser.praseAndExec(HostsExecutor.getSsh(),args);
		}
		else while(true){
			BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
			String str = stdin.readLine();				
			//卍解！！
			Parser.praseAndExec(HostsExecutor.getSsh(),str.split("( )+"));
		  }  
	}

	public static void prepare(String configUri) throws Exception {
		//配置文件和参数解析初始化
		  init(configUri);
		  //装配清单中的ssh对象列表
		  List<ListenableFuture<SshUtil>> futures = Assembler.assembly(
					getFetcher().getHosts(SshBatchMain.prop),
					prop.getInt("thread"),
					prop.getInt("timeout")
		  );				
		  HostsExecutor.getResults(futures);
	}	
		
	public static void main(String[] args) throws Exception{
		prepare("hosts.properties");
		fire(args);
	}
}
